package com.lankystar.todolist.page.group;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lankystar.common.Result;
import com.lankystar.todolist.dao.AccountMapper;
import com.lankystar.todolist.model.Account;
import com.lankystar.todolist.model.Groupinfo;
import com.lankystar.todolist.model.Groupuser;
import com.lankystar.todolist.model.Role;
import com.lankystar.todolist.service.IGroupService;

@Controller
@RequestMapping("/group")
public class GroupAction {

	@Autowired
	private IGroupService groupService;
	@Autowired
	private AccountMapper accountDao; 
	@Autowired
	private AccountMapper accountService;
	
	@RequestMapping("/toCreateGroup")
	public ModelAndView toCreateGroup(){
		return new ModelAndView("group/layout/createGroup.html");
	}
	
	@RequestMapping("/toAddGroupuser")
	public ModelAndView toAddGroupuser(){
		return new ModelAndView("group/layout/addGroupuser.html");
	}
	/**
	 * 查看组，组长
	 * @param req
	 * @param groupId
	 * @return
	 */
	@RequestMapping("/toGroup")
	public ModelAndView toGroup(HttpServletRequest req){
		List<Groupinfo> groupInfos=	groupService.selectGroup();
		List<Map<String,String>> accountlist=new ArrayList<Map<String,String>>(); 
		for (Groupinfo groupinfo : groupInfos) {
			Map<String, String> map=new HashMap<String, String>();
			map.put("name", groupinfo.getName());
			map.put("id", groupinfo.getId().toString());
			List<Groupuser> groups = groupService.selectGroupUserById(groupinfo.getId());
			for (Groupuser groupuser : groups) {
				if("LEADER".equals(groupuser.getRole())){
					map.put("userName", accountDao.selectByPrimaryKey(groupuser.getUserid()).getUsername());
				}
			}
			accountlist.add(map);
		}
		req.setAttribute("groupInfos", accountlist);
		return new ModelAndView("group/layout/group.html");
	}
	
	/**
	 * 创建组
	 * @param name
	 * @param createTime
	 * @return
	 */
	@RequestMapping(value="/createGroup",method=RequestMethod.POST)
	@ResponseBody
	public Result<String> createGroup(String name,String createTime){
		Result<String> result = new Result<>();
		Groupinfo groupinfo = groupService.selectGroupByName(name);
		if(groupinfo!=null){
			result.setCode(Result.FAIL);
			result.setMsg("小组名已存在，请重新输入小组名！！");
			return result;
		}else{
			groupinfo = new Groupinfo();
			groupinfo.setName(name);
			groupinfo.setCreatetime(createTime);
			groupService.createGroup(name, createTime);
			result.setCode(Result.OK);
			return result;
		}
	}
	
	/**
	 * 删除组
	 * @param id
	 * @param resp
	 */
	@RequestMapping("/delete")
	public void delete(Integer id,HttpServletResponse resp){
		/**
		 * 先删除组成员，在删除组
		 */
		groupService.deleteByGroupinfiId(id);
		try {
			/**
			 * 重定向，处理异常
			 */
			resp.sendRedirect("toGroup");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/showUser")
	public ModelAndView showUser(Integer groupId,HttpServletRequest req){
		if("".equals(groupId)||groupId==null){
		}else{
			List<Account> accountlist = accountService.selectAccountByGroupInfiId(groupId);
			
			req.setAttribute("accountlist", accountlist);
			req.setAttribute("groupId", groupId);
		}
		return new ModelAndView("group/layout/showUser.html");
	}
	
	/**
	 * 根据用户UserId删除组员
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="/deleteGroupuser")
	public void deleteGroupuser(HttpServletResponse resp,Integer userId,Integer groupId){
		groupService.deleteGroupuserByUserId(userId,groupId);
		try {
			resp.sendRedirect("/group/showUser?groupId="+groupId+"");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 添加组员
	 * @param userId
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value="/addGroupuser")
	public void addGroupuser(HttpServletResponse resp,Integer userId,Integer groupId){
		if(userId==null||groupId==null){
		}else{
			groupService.createGroupUser(groupId, userId, Role.MEMBER.toString());
			try {
				resp.sendRedirect("/group/showGroupuser?groupId="+groupId+"");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@RequestMapping(value="/showGroupuser")
	public ModelAndView showGroupuser(HttpServletRequest req,Integer groupId) {
		List<Account> accountlist = accountService.selectAccounts();
		Account record = (Account) req.getSession().getAttribute("user");
		List<Account> accounts = accountService.selectAccountByGroupInfiId(groupId);
		List<Object> list = new ArrayList<>();
		for (Account account : accountlist) {
			
			for (Account a : accounts) {
				if(a.getId()==account.getId()){
					list.add(account);
				}
			}
			/**
			 * 不展示权限高于或等于登陆者的用户
			 */
			if("SUPERADMIN".equals(record.getRole())){
				if("SUPERADMIN".equals(account.getRole())){
					list.add(account);
				}
			}
			if("ADMIN".equals(record.getRole())){
				if("ADMIN".equals(account.getRole())||"SUPERADMIN".equals(account.getRole())){
					list.add(account);
				}
			}
		}
		accountlist.removeAll(list);
		req.setAttribute("accountlist", accountlist);
		req.setAttribute("groupId", groupId);
		return new ModelAndView("group/layout/addGroupuser.html");
	}
	
	@RequestMapping("/toRole")
	public ModelAndView toRole(HttpServletRequest req,Integer groupId){
		List<Groupuser> groupUsers=	groupService.selectGroupUserById(groupId);
		List<Map<String,String>> accountlist=new ArrayList<Map<String,String>>(); 
		for (Groupuser groupuser : groupUsers) {
			Map<String, String> map=new HashMap<String, String>();
			map.put("role", groupuser.getRole());
			map.put("groupId", String.valueOf(groupuser.getGroupid()));
			map.put("userId", String.valueOf(groupuser.getUserid()));
			List<Account> accounts = accountService.selectAccountByGroupInfiId(groupId);
			for (Account account : accounts) {
				map.put("username", account.getUsername());
				map.put("nickname", account.getNickname());
				map.put("accountRole", account.getRole());
			}
			accountlist.add(map);
		}
		req.setAttribute("groupuser", accountlist);
		return new ModelAndView("group/layout/role.html");
	}
	
	@RequestMapping(value="/updateGroupuser",method=RequestMethod.POST)
	@ResponseBody
	public Result<String> updateGroupuser(Integer userId,Integer groupId,String role){
		Result<String> result = new Result<>();
		if(userId==null||groupId==null){
			result.setCode(Result.FAIL);
			result.setMsg("为获取到数据！！");
			return result;
		}else{
			Groupuser groupuser = groupService.seleteGroupuserByUserIdAndGroupId(userId, groupId);
			List<Groupuser> groupusers = groupService.selectGroupUserById(groupId);
			for (Groupuser group : groupusers) {
				if(group.getRole().equals(Role.LEADER.toString())){
					group.setRole(Role.MEMBER.toString());
					groupService.upateGroupuser(group);
				}
			}
			if(Role.MEMBER.toString().equals(role)){
				groupuser.setRole(Role.LEADER.toString());
			}else{
				groupuser.setRole(Role.MEMBER.toString());
			}
			groupService.upateGroupuser(groupuser);
			result.setCode(Result.OK);
			return result;
		}
	}
}
